package com.weixin.engine.daily;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Scanner;

/**
 * 测试MappedByteBuffer
 *
 * @author wangchunhui
 * @date 2022/2/17 16:14
 */
public class MappedByteBufferTest {
    public static void main(String[] args) {

        File file = new File("ch_engine/src/main/resources/data.txt");
        long len = file.length();
        byte[] ds = new byte[(int) len];

        try {
            // 可以发现这里定义了四种模式：R RW RWD RWS
            // r	以只读的方式打开文本，也就意味着不能用write来操作文件
            // rw	读操作和写操作都是允许的
            // rws	每当进行写操作，同步的刷新到磁盘，刷新内容和元数据
            // rwd	每当进行写操作，同步的刷新到磁盘，刷新内容
            MappedByteBuffer mappedByteBuffer = new RandomAccessFile(file, "r")
                    .getChannel()
                    .map(FileChannel.MapMode.READ_ONLY, 0, len);
            for (int offset = 0; offset < len; offset++) {
                byte b = mappedByteBuffer.get();
                ds[offset] = b;
            }

            Scanner scan = new Scanner(new ByteArrayInputStream(ds)).useDelimiter(" ");
            while (scan.hasNext()) {
                System.out.print(scan.next());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}